/**
 * 桌面宠物管理器
 * 负责宠物的数据管理、状态更新、交互逻辑等
 */

import goldManager from './gold-manager.js'

class DesktopPetManager {
  constructor() {
    this.petData = null
    this.isInitialized = false
    this.updateTimer = null
    this.eventListeners = new Map()
    
    // 自动化功能金币消耗配置
    this.automationCosts = {
      autoFeed: 10,        // 自动喂食：10金币/次
      autoPlay: 15,        // 自动玩耍：15金币/次
      autoRest: 5,         // 自动休息：5金币/次
      autoClean: 8,        // 自动清洁：8金币/次
      autoHeal: 20,        // 自动治疗：20金币/次
      autoMoodBoost: 12    // 自动提升心情：12金币/次
    }
    
    // 自动化套餐配置
    this.automationPackages = {
      basic: {
        name: '基础套餐',
        features: ['autoFeed', 'autoRest'],
        price: 100,
        duration: 24 * 60 * 60 * 1000 // 24小时
      },
      advanced: {
        name: '高级套餐',
        features: ['autoFeed', 'autoPlay', 'autoRest', 'autoClean'],
        price: 200,
        duration: 24 * 60 * 60 * 1000 // 24小时
      },
      premium: {
        name: '豪华套餐',
        features: ['autoFeed', 'autoPlay', 'autoRest', 'autoClean', 'autoHeal', 'autoMoodBoost'],
        price: 350,
        duration: 24 * 60 * 60 * 1000 // 24小时
      }
    }
    
    // 默认宠物数据
    this.defaultPetData = {
      id: 1,
      name: '小萌宠',
      emoji: '🐱',
      avatar: '',
      level: 1,
      exp: 0,
      maxExp: 100,
      mood: 80,
      hunger: 70,
      energy: 60,
      cleanliness: 80,  // 新增清洁度
      health: 100,      // 新增健康值
      isActive: true,
      lastUpdateTime: Date.now(),
      totalPlayTime: 0,
      interactionCount: 0,
      achievements: [],
      settings: {
        autoFeed: false,
        autoPlay: false,
        autoRest: false,
        autoClean: false,
        autoHeal: false,
        autoMoodBoost: false,
        showBubbles: true,
        soundEnabled: true,
        voiceRecognition: false
      },
      automationPackage: null, // 当前激活的自动化套餐
      automationExpireTime: null // 套餐过期时间
    }
    
    this.init()
  }
  
  /**
   * 初始化宠物管理器
   */
  init() {
    try {
      this.loadPetData()
      this.startAutoUpdate()
      this.isInitialized = true
      console.log('桌面宠物管理器初始化成功')
    } catch (error) {
      console.error('桌面宠物管理器初始化失败:', error)
      this.petData = { ...this.defaultPetData }
      this.savePetData()
    }
  }
  
  /**
   * 加载宠物数据
   */
  loadPetData() {
    try {
      const savedData = uni.getStorageSync('desktop_pet_data')
      if (savedData) {
        this.petData = { ...this.defaultPetData, ...savedData }
        console.log('宠物数据加载成功:', this.petData.name)
      } else {
        this.petData = { ...this.defaultPetData }
        this.savePetData()
        console.log('使用默认宠物数据')
      }
    } catch (error) {
      console.error('加载宠物数据失败:', error)
      this.petData = { ...this.defaultPetData }
    }
  }
  
  /**
   * 保存宠物数据
   */
  savePetData() {
    try {
      this.petData.lastUpdateTime = Date.now()
      uni.setStorageSync('desktop_pet_data', this.petData)
      this.emit('pet-data-updated', this.petData)
    } catch (error) {
      console.error('保存宠物数据失败:', error)
    }
  }
  
  /**
   * 获取宠物数据
   */
  getPetData() {
    return this.petData
  }
  
  /**
   * 更新宠物数据
   */
  updatePetData(updates) {
    if (!this.petData) return
    
    Object.assign(this.petData, updates)
    this.savePetData()
  }
  
  /**
   * 喂食宠物
   */
  feedPet() {
    if (!this.petData || this.petData.hunger >= 100) {
      return {
        success: false,
        message: '宠物已经吃饱了！',
        data: this.petData
      }
    }
    
    const oldHunger = this.petData.hunger
    this.petData.hunger = Math.min(100, this.petData.hunger + 30)
    this.petData.mood = Math.min(100, this.petData.mood + 10)
    this.petData.interactionCount++
    
    // 检查是否升级
    const leveledUp = this.checkLevelUp()
    
    this.savePetData()
    
    return {
      success: true,
      message: `喂食成功！饥饿值 +${this.petData.hunger - oldHunger}`,
      data: this.petData,
      leveledUp
    }
  }
  
  /**
   * 与宠物玩耍
   */
  playWithPet() {
    if (!this.petData || this.petData.energy < 10) {
      return {
        success: false,
        message: '宠物太累了，需要休息！',
        data: this.petData
      }
    }
    
    const oldEnergy = this.petData.energy
    const oldMood = this.petData.mood
    const oldExp = this.petData.exp
    
    this.petData.energy = Math.max(0, this.petData.energy - 15)
    this.petData.mood = Math.min(100, this.petData.mood + 20)
    this.petData.exp = Math.min(this.petData.maxExp, this.petData.exp + 10)
    this.petData.interactionCount++
    
    // 检查是否升级
    const leveledUp = this.checkLevelUp()
    
    this.savePetData()
    
    return {
      success: true,
      message: `玩耍成功！精力 -${oldEnergy - this.petData.energy}，心情 +${this.petData.mood - oldMood}，经验 +${this.petData.exp - oldExp}`,
      data: this.petData,
      leveledUp
    }
  }
  
  /**
   * 让宠物休息
   */
  restPet() {
    if (!this.petData || this.petData.energy >= 100) {
      return {
        success: false,
        message: '宠物不需要休息！',
        data: this.petData
      }
    }
    
    const oldEnergy = this.petData.energy
    this.petData.energy = Math.min(100, this.petData.energy + 40)
    this.petData.mood = Math.min(100, this.petData.mood + 5)
    this.petData.interactionCount++
    
    this.savePetData()
    
    return {
      success: true,
      message: `休息成功！精力 +${this.petData.energy - oldEnergy}`,
      data: this.petData
    }
  }
  
  /**
   * 检查升级
   */
  checkLevelUp() {
    if (!this.petData || this.petData.exp < this.petData.maxExp) {
      return false
    }
    
    this.petData.level++
    this.petData.exp = 0
    this.petData.maxExp = Math.floor(this.petData.maxExp * 1.2)
    
    // 升级奖励
    this.petData.mood = Math.min(100, this.petData.mood + 20)
    this.petData.energy = Math.min(100, this.petData.energy + 15)
    this.petData.hunger = Math.min(100, this.petData.hunger + 10)
    
    // 解锁新表情
    this.unlockNewEmoji()
    
    this.savePetData()
    this.emit('pet-level-up', {
      level: this.petData.level,
      newEmoji: this.petData.emoji
    })
    
    return true
  }
  
  /**
   * 解锁新表情
   */
  unlockNewEmoji() {
    const emojis = ['🐱', '🐶', '🐰', '🐸', '🐧', '🦊', '🐨', '🐼', '🦄', '🐙']
    const currentIndex = emojis.indexOf(this.petData.emoji)
    
    if (currentIndex < emojis.length - 1) {
      this.petData.emoji = emojis[currentIndex + 1]
    }
  }
  
  /**
   * 开始自动更新
   */
  startAutoUpdate() {
    // 每分钟更新一次状态
    this.updateTimer = setInterval(() => {
      this.autoUpdateStatus()
    }, 60000)
  }
  
  /**
   * 自动更新状态
   */
  autoUpdateStatus() {
    if (!this.petData) return
    
    const now = Date.now()
    const timeDiff = now - this.petData.lastUpdateTime
    
    // 根据时间差计算状态变化
    const hoursPassed = timeDiff / (1000 * 60 * 60)
    
    // 饥饿度随时间减少
    this.petData.hunger = Math.max(0, this.petData.hunger - Math.floor(hoursPassed * 2))
    
    // 精力随时间恢复
    this.petData.energy = Math.min(100, this.petData.energy + Math.floor(hoursPassed * 1))
    
    // 心情根据其他状态调整
    if (this.petData.hunger < 20) {
      this.petData.mood = Math.max(0, this.petData.mood - 5)
    } else if (this.petData.hunger > 80) {
      this.petData.mood = Math.min(100, this.petData.mood + 2)
    }
    
    if (this.petData.energy < 15) {
      this.petData.mood = Math.max(0, this.petData.mood - 3)
    }
    
    // 检查自动功能
    this.checkAutoActions()
    
    // 检查成就
    this.checkAchievements()
    
    this.savePetData()
    this.emit('pet-status-updated', this.petData)
  }
  
  /**
   * 检查自动功能（需要传入goldManager）
   */
  checkAutoActions(goldManager) {
    if (!this.petData || !this.petData.settings) return
    if (!goldManager) return // 没有金币管理器就不执行
    
    // 检查套餐是否过期
    this.checkAutomationPackageExpiry()
    
    try {
      // 自动喂食
      if (this.petData.settings.autoFeed && this.petData.hunger < 30) {
        const cost = this.automationCosts.autoFeed
        if (goldManager.hasEnoughGold(cost)) {
          console.log('自动喂食触发')
          goldManager.spendGold(cost, '宠物自动喂食')
          this.petData.hunger = Math.min(100, this.petData.hunger + 20)
          this.petData.mood = Math.min(100, this.petData.mood + 5)
          this.emit('auto-action', { 
            type: 'feed', 
            message: '自动喂食了宠物',
            cost: cost
          })
        } else {
          // 金币不足，关闭自动喂食
          this.petData.settings.autoFeed = false
          this.savePetData()
          this.emit('auto-action-failed', { 
            type: 'feed', 
            message: '金币不足，自动喂食已关闭',
            requiredGold: cost
          })
        }
      }
      
      // 自动玩耍
      if (this.petData.settings.autoPlay && this.petData.energy > 50 && this.petData.mood < 70) {
        const cost = this.automationCosts.autoPlay
        if (goldManager.hasEnoughGold(cost)) {
          console.log('自动玩耍触发')
          goldManager.spendGold(cost, '宠物自动玩耍')
          this.petData.energy = Math.max(0, this.petData.energy - 10)
          this.petData.mood = Math.min(100, this.petData.mood + 15)
          this.petData.exp = Math.min(this.petData.maxExp, this.petData.exp + 5)
          this.emit('auto-action', { 
            type: 'play', 
            message: '自动与宠物玩耍了',
            cost: cost
          })
        } else {
          this.petData.settings.autoPlay = false
          this.savePetData()
          this.emit('auto-action-failed', { 
            type: 'play', 
            message: '金币不足，自动玩耍已关闭',
            requiredGold: cost
          })
        }
      }
      
      // 自动休息
      if (this.petData.settings.autoRest && this.petData.energy < 20) {
        const cost = this.automationCosts.autoRest
        if (goldManager.hasEnoughGold(cost)) {
          console.log('自动休息触发')
          goldManager.spendGold(cost, '宠物自动休息')
          this.petData.energy = Math.min(100, this.petData.energy + 30)
          this.emit('auto-action', { 
            type: 'rest', 
            message: '宠物自动休息了',
            cost: cost
          })
        } else {
          this.petData.settings.autoRest = false
          this.savePetData()
          this.emit('auto-action-failed', { 
            type: 'rest', 
            message: '金币不足，自动休息已关闭',
            requiredGold: cost
          })
        }
      }
      
      // 自动清洁
      if (this.petData.settings.autoClean && this.petData.cleanliness < 40) {
        const cost = this.automationCosts.autoClean
        if (goldManager.hasEnoughGold(cost)) {
          console.log('自动清洁触发')
          goldManager.spendGold(cost, '宠物自动清洁')
          this.petData.cleanliness = Math.min(100, this.petData.cleanliness + 40)
          this.petData.mood = Math.min(100, this.petData.mood + 5)
          this.emit('auto-action', { 
            type: 'clean', 
            message: '自动清洁了宠物',
            cost: cost
          })
        } else {
          this.petData.settings.autoClean = false
          this.savePetData()
          this.emit('auto-action-failed', { 
            type: 'clean', 
            message: '金币不足，自动清洁已关闭',
            requiredGold: cost
          })
        }
      }
      
      // 自动治疗
      if (this.petData.settings.autoHeal && this.petData.health < 60) {
        const cost = this.automationCosts.autoHeal
        if (goldManager.hasEnoughGold(cost)) {
          console.log('自动治疗触发')
          goldManager.spendGold(cost, '宠物自动治疗')
          this.petData.health = Math.min(100, this.petData.health + 40)
          this.petData.mood = Math.min(100, this.petData.mood + 10)
          this.emit('auto-action', { 
            type: 'heal', 
            message: '自动治疗了宠物',
            cost: cost
          })
        } else {
          this.petData.settings.autoHeal = false
          this.savePetData()
          this.emit('auto-action-failed', { 
            type: 'heal', 
            message: '金币不足，自动治疗已关闭',
            requiredGold: cost
          })
        }
      }
      
      // 自动提升心情
      if (this.petData.settings.autoMoodBoost && this.petData.mood < 50) {
        const cost = this.automationCosts.autoMoodBoost
        if (goldManager.hasEnoughGold(cost)) {
          console.log('自动提升心情触发')
          goldManager.spendGold(cost, '宠物自动提升心情')
          this.petData.mood = Math.min(100, this.petData.mood + 25)
          this.emit('auto-action', { 
            type: 'moodBoost', 
            message: '自动提升了宠物心情',
            cost: cost
          })
        } else {
          this.petData.settings.autoMoodBoost = false
          this.savePetData()
          this.emit('auto-action-failed', { 
            type: 'moodBoost', 
            message: '金币不足，自动提升心情已关闭',
            requiredGold: cost
          })
        }
      }
    } catch (error) {
      console.error('自动功能执行失败:', error)
    }
  }
  
  /**
   * 检查自动化套餐是否过期
   */
  checkAutomationPackageExpiry() {
    if (this.petData.automationPackage && this.petData.automationExpireTime) {
      const now = Date.now()
      if (now > this.petData.automationExpireTime) {
        // 套餐已过期，关闭所有自动化功能
        const packageConfig = this.automationPackages[this.petData.automationPackage]
        if (packageConfig) {
          packageConfig.features.forEach(feature => {
            this.petData.settings[feature] = false
          })
        }
        
        this.petData.automationPackage = null
        this.petData.automationExpireTime = null
        this.savePetData()
        
        this.emit('automation-package-expired', {
          message: '自动化套餐已过期'
        })
      }
    }
  }
  
  /**
   * 购买自动化套餐
   */
  purchaseAutomationPackage(packageType, goldManager) {
    const packageConfig = this.automationPackages[packageType]
    if (!packageConfig) {
      return {
        success: false,
        message: '无效的套餐类型'
      }
    }
    
    if (!goldManager) {
      return {
        success: false,
        message: '金币管理器未初始化'
      }
    }
    
    try {
      // 检查金币是否足够
      if (!goldManager.hasEnoughGold(packageConfig.price)) {
        return {
          success: false,
          message: `金币不足，需要${packageConfig.price}金币`,
          requiredGold: packageConfig.price,
          currentGold: goldManager.getCurrentGold()
        }
      }
      
      // 扣除金币
      const spent = goldManager.spendGold(packageConfig.price, `购买${packageConfig.name}`)
      if (!spent) {
        return {
          success: false,
          message: '购买失败，请重试'
        }
      }
      
      // 激活套餐
      this.petData.automationPackage = packageType
      this.petData.automationExpireTime = Date.now() + packageConfig.duration
      
      // 开启套餐包含的所有功能
      packageConfig.features.forEach(feature => {
        this.petData.settings[feature] = true
      })
      
      this.savePetData()
      
      this.emit('automation-package-purchased', {
        packageType,
        packageConfig,
        expireTime: this.petData.automationExpireTime
      })
      
      return {
        success: true,
        message: `成功购买${packageConfig.name}`,
        packageConfig,
        expireTime: this.petData.automationExpireTime
      }
    } catch (error) {
      console.error('购买自动化套餐失败:', error)
      return {
        success: false,
        message: '购买失败，请重试'
      }
    }
  }
  
  /**
   * 获取自动化套餐信息
   */
  getAutomationPackageInfo(packageType) {
    return this.automationPackages[packageType] || null
  }
  
  /**
   * 获取所有自动化套餐
   */
  getAllAutomationPackages() {
    return this.automationPackages
  }
  
  /**
   * 获取当前激活的套餐信息
   */
  getCurrentAutomationPackage() {
    if (!this.petData.automationPackage) {
      return null
    }
    
    const packageConfig = this.automationPackages[this.petData.automationPackage]
    if (!packageConfig) {
      return null
    }
    
    const remainingTime = this.petData.automationExpireTime - Date.now()
    
    return {
      type: this.petData.automationPackage,
      config: packageConfig,
      expireTime: this.petData.automationExpireTime,
      remainingTime: Math.max(0, remainingTime),
      isExpired: remainingTime <= 0
    }
  }
  
  /**
   * 获取自动化功能消耗配置
   */
  getAutomationCosts() {
    return this.automationCosts
  }
  
  /**
   * 检查成就
   */
  checkAchievements() {
    const achievements = []
    
    // 基础成就
    if (this.petData.interactionCount >= 1 && !this.petData.achievements.includes('first_interaction')) {
      achievements.push('first_interaction')
    }
    if (this.petData.interactionCount >= 10 && !this.petData.achievements.includes('interaction_starter')) {
      achievements.push('interaction_starter')
    }
    if (this.petData.interactionCount >= 50 && !this.petData.achievements.includes('interaction_lover')) {
      achievements.push('interaction_lover')
    }
    if (this.petData.interactionCount >= 100 && !this.petData.achievements.includes('interaction_master')) {
      achievements.push('interaction_master')
    }
    if (this.petData.interactionCount >= 500 && !this.petData.achievements.includes('interaction_legend')) {
      achievements.push('interaction_legend')
    }
    
    // 等级成就
    if (this.petData.level >= 2 && !this.petData.achievements.includes('level_2')) {
      achievements.push('level_2')
    }
    if (this.petData.level >= 5 && !this.petData.achievements.includes('level_5')) {
      achievements.push('level_5')
    }
    if (this.petData.level >= 10 && !this.petData.achievements.includes('level_10')) {
      achievements.push('level_10')
    }
    if (this.petData.level >= 20 && !this.petData.achievements.includes('level_20')) {
      achievements.push('level_20')
    }
    if (this.petData.level >= 50 && !this.petData.achievements.includes('level_50')) {
      achievements.push('level_50')
    }
    
    // 状态成就
    if (this.petData.mood >= 100 && !this.petData.achievements.includes('happy_pet')) {
      achievements.push('happy_pet')
    }
    if (this.petData.hunger >= 100 && !this.petData.achievements.includes('well_fed')) {
      achievements.push('well_fed')
    }
    if (this.petData.energy >= 100 && !this.petData.achievements.includes('energetic')) {
      achievements.push('energetic')
    }
    if (this.petData.cleanliness >= 100 && !this.petData.achievements.includes('sparkling_clean')) {
      achievements.push('sparkling_clean')
    }
    if (this.petData.health >= 100 && !this.petData.achievements.includes('perfect_health')) {
      achievements.push('perfect_health')
    }
    
    // 全属性满值
    if (this.petData.mood >= 100 && this.petData.hunger >= 100 && 
        this.petData.energy >= 100 && this.petData.cleanliness >= 100 && 
        this.petData.health >= 100 && !this.petData.achievements.includes('perfect_state')) {
      achievements.push('perfect_state')
    }
    
    // 照顾成就
    const feedCount = this.petData.feedCount || 0
    if (feedCount >= 10 && !this.petData.achievements.includes('food_lover')) {
      achievements.push('food_lover')
    }
    if (feedCount >= 100 && !this.petData.achievements.includes('gourmet')) {
      achievements.push('gourmet')
    }
    
    const playCount = this.petData.playCount || 0
    if (playCount >= 10 && !this.petData.achievements.includes('playful')) {
      achievements.push('playful')
    }
    if (playCount >= 100 && !this.petData.achievements.includes('play_master')) {
      achievements.push('play_master')
    }
    
    // 自动化成就
    if (this.petData.settings.autoFeed && !this.petData.achievements.includes('automation_beginner')) {
      achievements.push('automation_beginner')
    }
    if (this.petData.automationPackage && !this.petData.achievements.includes('package_buyer')) {
      achievements.push('package_buyer')
    }
    
    // 时间成就
    const petAge = this.petData.age || 0
    if (petAge >= 1 && !this.petData.achievements.includes('one_day')) {
      achievements.push('one_day')
    }
    if (petAge >= 7 && !this.petData.achievements.includes('one_week')) {
      achievements.push('one_week')
    }
    if (petAge >= 30 && !this.petData.achievements.includes('one_month')) {
      achievements.push('one_month')
    }
    if (petAge >= 100 && !this.petData.achievements.includes('centenarian')) {
      achievements.push('centenarian')
    }
    
    // 特殊成就
    if (this.petData.mood < 10 && !this.petData.achievements.includes('crisis_survived')) {
      achievements.push('crisis_survived')
    }
    
    if (achievements.length > 0) {
      this.petData.achievements.push(...achievements)
      this.emit('achievement-unlocked', achievements)
    }
  }
  
  /**
   * 获取所有成就定义
   */
  getAllAchievementsDefinition() {
    return {
      // 基础互动成就
      'first_interaction': {
        name: '初次相遇',
        description: '第一次与宠物互动',
        icon: '👋',
        category: 'basic',
        requirement: '互动1次'
      },
      'interaction_starter': {
        name: '互动新手',
        description: '与宠物互动10次',
        icon: '🎯',
        category: 'basic',
        requirement: '互动10次'
      },
      'interaction_lover': {
        name: '互动爱好者',
        description: '与宠物互动50次',
        icon: '💖',
        category: 'basic',
        requirement: '互动50次'
      },
      'interaction_master': {
        name: '互动大师',
        description: '与宠物互动100次',
        icon: '🏆',
        category: 'basic',
        requirement: '互动100次'
      },
      'interaction_legend': {
        name: '互动传说',
        description: '与宠物互动500次',
        icon: '👑',
        category: 'basic',
        requirement: '互动500次'
      },
      
      // 等级成就
      'level_2': {
        name: '崭露头角',
        description: '宠物达到2级',
        icon: '⭐',
        category: 'level',
        requirement: '等级2'
      },
      'level_5': {
        name: '成长之星',
        description: '宠物达到5级',
        icon: '🌟',
        category: 'level',
        requirement: '等级5'
      },
      'level_10': {
        name: '卓越宠物',
        description: '宠物达到10级',
        icon: '✨',
        category: 'level',
        requirement: '等级10'
      },
      'level_20': {
        name: '传奇宠物',
        description: '宠物达到20级',
        icon: '💫',
        category: 'level',
        requirement: '等级20'
      },
      'level_50': {
        name: '终极进化',
        description: '宠物达到50级',
        icon: '🔥',
        category: 'level',
        requirement: '等级50'
      },
      
      // 状态成就
      'happy_pet': {
        name: '快乐宠物',
        description: '心情达到100%',
        icon: '😊',
        category: 'status',
        requirement: '心情100%'
      },
      'well_fed': {
        name: '吃饱喝足',
        description: '饥饿度达到100%',
        icon: '🍖',
        category: 'status',
        requirement: '饥饿度100%'
      },
      'energetic': {
        name: '精力充沛',
        description: '精力达到100%',
        icon: '⚡',
        category: 'status',
        requirement: '精力100%'
      },
      'sparkling_clean': {
        name: '一尘不染',
        description: '清洁度达到100%',
        icon: '✨',
        category: 'status',
        requirement: '清洁度100%'
      },
      'perfect_health': {
        name: '健康满分',
        description: '健康值达到100%',
        icon: '💚',
        category: 'status',
        requirement: '健康值100%'
      },
      'perfect_state': {
        name: '完美状态',
        description: '所有属性同时达到100%',
        icon: '🌈',
        category: 'status',
        requirement: '全属性100%'
      },
      
      // 照顾成就
      'food_lover': {
        name: '美食爱好者',
        description: '喂食宠物10次',
        icon: '🍗',
        category: 'care',
        requirement: '喂食10次'
      },
      'gourmet': {
        name: '美食家',
        description: '喂食宠物100次',
        icon: '🍽️',
        category: 'care',
        requirement: '喂食100次'
      },
      'playful': {
        name: '爱玩',
        description: '与宠物玩耍10次',
        icon: '🎾',
        category: 'care',
        requirement: '玩耍10次'
      },
      'play_master': {
        name: '玩耍大师',
        description: '与宠物玩耍100次',
        icon: '🎮',
        category: 'care',
        requirement: '玩耍100次'
      },
      
      // 自动化成就
      'automation_beginner': {
        name: '自动化新手',
        description: '首次开启自动化功能',
        icon: '🤖',
        category: 'automation',
        requirement: '开启任意自动化'
      },
      'package_buyer': {
        name: '套餐购买者',
        description: '购买自动化套餐',
        icon: '🎁',
        category: 'automation',
        requirement: '购买套餐'
      },
      
      // 时间成就
      'one_day': {
        name: '一日之交',
        description: '养育宠物1天',
        icon: '📅',
        category: 'time',
        requirement: '养育1天'
      },
      'one_week': {
        name: '一周陪伴',
        description: '养育宠物7天',
        icon: '📆',
        category: 'time',
        requirement: '养育7天'
      },
      'one_month': {
        name: '月度守护',
        description: '养育宠物30天',
        icon: '📅',
        category: 'time',
        requirement: '养育30天'
      },
      'centenarian': {
        name: '百日陪伴',
        description: '养育宠物100天',
        icon: '💯',
        category: 'time',
        requirement: '养育100天'
      },
      
      // 特殊成就
      'crisis_survived': {
        name: '渡过难关',
        description: '从极度不开心中恢复',
        icon: '🌅',
        category: 'special',
        requirement: '心情<10后恢复'
      }
    }
  }
  
  /**
   * 获取成就信息
   */
  getAchievementInfo(achievementId) {
    const allAchievements = this.getAllAchievementsDefinition()
    return allAchievements[achievementId] || null
  }
  
  /**
   * 按分类获取成就
   */
  getAchievementsByCategory(category) {
    const allAchievements = this.getAllAchievementsDefinition()
    const result = []
    
    for (const [id, info] of Object.entries(allAchievements)) {
      if (info.category === category) {
        result.push({
          id,
          ...info,
          unlocked: this.petData.achievements.includes(id)
        })
      }
    }
    
    return result
  }
  
  /**
   * 获取所有成就（带解锁状态）
   */
  getAllAchievementsWithStatus() {
    const allAchievements = this.getAllAchievementsDefinition()
    const result = []
    
    for (const [id, info] of Object.entries(allAchievements)) {
      result.push({
        id,
        ...info,
        unlocked: this.petData.achievements.includes(id)
      })
    }
    
    return result
  }
  
  /**
   * 获取成就统计
   */
  getAchievementStats() {
    const allAchievements = this.getAllAchievementsDefinition()
    const total = Object.keys(allAchievements).length
    const unlocked = this.petData.achievements.length
    
    const categories = {
      basic: { total: 0, unlocked: 0, name: '基础互动' },
      level: { total: 0, unlocked: 0, name: '等级成长' },
      status: { total: 0, unlocked: 0, name: '状态完美' },
      care: { total: 0, unlocked: 0, name: '细心照顾' },
      automation: { total: 0, unlocked: 0, name: '自动化' },
      time: { total: 0, unlocked: 0, name: '时间陪伴' },
      special: { total: 0, unlocked: 0, name: '特殊成就' }
    }
    
    for (const [id, info] of Object.entries(allAchievements)) {
      if (categories[info.category]) {
        categories[info.category].total++
        if (this.petData.achievements.includes(id)) {
          categories[info.category].unlocked++
        }
      }
    }
    
    return {
      total,
      unlocked,
      progress: Math.floor((unlocked / total) * 100),
      categories
    }
  }
  
  /**
   * 获取宠物状态描述
   */
  getPetStatusDescription() {
    if (!this.petData) return '未知状态'
    
    const { mood, hunger, energy } = this.petData
    
    if (hunger < 20) return '饥饿'
    if (energy < 15) return '疲惫'
    if (mood < 30) return '不开心'
    if (mood > 80 && hunger > 70 && energy > 60) return '非常开心'
    if (mood > 60) return '开心'
    
    return '正常'
  }
  
  /**
   * 获取随机对话
   */
  getRandomDialogue() {
    const status = this.getPetStatusDescription()
    
    const dialogues = {
      '饥饿': [
        '主人，我饿了...',
        '能给我一些食物吗？',
        '肚子咕咕叫了...'
      ],
      '疲惫': [
        '我好累啊...',
        '让我休息一下吧...',
        'Zzz...'
      ],
      '不开心': [
        '我不开心...',
        '能陪陪我吗？',
        '心情不好...'
      ],
      '非常开心': [
        '主人最好了！',
        '今天真开心！',
        '我爱你，主人！'
      ],
      '开心': [
        '主人，你好！',
        '今天也要加油哦！',
        '需要我帮忙吗？'
      ],
      '正常': [
        '主人，我在这里！',
        '今天过得怎么样？',
        '点击我可以和我互动！'
      ]
    }
    
    const statusDialogues = dialogues[status] || dialogues['正常']
    return statusDialogues[Math.floor(Math.random() * statusDialogues.length)]
  }
  
  /**
   * 设置宠物设置
   */
  updatePetSettings(settings) {
    if (!this.petData) return
    
    Object.assign(this.petData.settings, settings)
    this.savePetData()
  }
  
  /**
   * 获取宠物设置
   */
  getPetSettings() {
    return this.petData ? this.petData.settings : this.defaultPetData.settings
  }
  
  /**
   * 重置宠物数据
   */
  resetPetData() {
    this.petData = { ...this.defaultPetData }
    this.savePetData()
    this.emit('pet-reset', this.petData)
  }
  
  /**
   * 导出宠物数据
   */
  exportPetData() {
    if (!this.petData) return null
    
    return {
      ...this.petData,
      exportTime: Date.now(),
      version: '1.0.0'
    }
  }
  
  /**
   * 导入宠物数据
   */
  importPetData(data) {
    try {
      if (data && typeof data === 'object') {
        this.petData = { ...this.defaultPetData, ...data }
        this.savePetData()
        this.emit('pet-data-imported', this.petData)
        return true
      }
      return false
    } catch (error) {
      console.error('导入宠物数据失败:', error)
      return false
    }
  }
  
  /**
   * 事件监听
   */
  on(event, callback) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, [])
    }
    this.eventListeners.get(event).push(callback)
  }
  
  /**
   * 移除事件监听
   */
  off(event, callback) {
    if (this.eventListeners.has(event)) {
      const listeners = this.eventListeners.get(event)
      const index = listeners.indexOf(callback)
      if (index > -1) {
        listeners.splice(index, 1)
      }
    }
  }
  
  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.eventListeners.has(event)) {
      this.eventListeners.get(event).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('事件回调执行失败:', error)
        }
      })
    }
  }
  
  /**
   * 销毁管理器
   */
  destroy() {
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
      this.updateTimer = null
    }
    
    this.eventListeners.clear()
    this.isInitialized = false
  }
}

// 创建单例实例
const desktopPetManager = new DesktopPetManager()

export default desktopPetManager
